﻿using System;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ClassicPassWd
{
    /// <summary>
    /// CaesarPassword.xaml 的交互逻辑
    /// </summary>
    public partial class CaesarPassword : UserControl
    {
        private char[] alphaCharsUpper =
        {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
            'V', 'W', 'X', 'Y', 'Z'
        };

        public CaesarPassword()
        {
            InitializeComponent();
        }

        private void BoxProclaim_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            BoxPassword.Text = "";
            if (BoxProclaim.Text != "")
                GetPassword((int) Slider.Value);
        }

        private void GetPassword(int offset)
        {
            string str1 = BoxProclaim.Text.Replace(" ", "");
            Slider.Maximum = BoxProclaim.Text == "" ? 0 : str1.Length;
            char[] temp = str1.ToCharArray();
            char[] str2 = String.Copy(str1).ToCharArray();
            for (int i = 0; i < str2.Length; i++)
            {
                str2[i] = alphaCharsUpper[((str1[i] - 65) + offset) % 26];
            }

            BoxPassword.Text = new string(str2);
        }

        private void Slider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            BoxPassword.Text = "";
            if (BoxProclaim.Text != "")
                GetPassword((int) Slider.Value);
        }

        private void BoxProclaim_OnPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Space)
            {
                e.Handled = false;
                return;
            }

            e.Handled = new Regex("[^A-Za-z]").IsMatch(GetCharFromKey.KeyChars(e.Key).ToString());
        }
    }
}